package cn.iocoder.yudao.module.iot.controller.admin.scene;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneActionDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneConditionDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.user.IotUserDO;
import cn.iocoder.yudao.module.iot.dal.mysql.scene.IotSceneActionMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.scene.IotSceneConditionMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.scene.IotSceneMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.device.IotDeviceMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.product.IotProductMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.user.IotUserMapper;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import jakarta.annotation.Resource;
import java.util.*;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.jdbc.core.JdbcTemplate;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/iot/scene")
@Slf4j
public class IotAdminSceneController {
    @Resource private IotSceneActionMapper actionMapper;
    @Resource private IotSceneConditionMapper conditionMapper;
    @Resource private IotSceneMapper sceneMapper;
    @Resource private IotDeviceMapper deviceMapper;
    @Resource private IotProductMapper productMapper;
    @Resource private IotUserMapper userMapper;

    @Resource private JdbcTemplate jdbcTemplate;

    @GetMapping("/all-scene-actions")
    public CommonResult<List<Map<String, Object>>> getAllUserSceneActions() {
        try {
            // 获取所有场景
            List<IotSceneDO> scenes = sceneMapper.selectList(null);
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (IotSceneDO scene : scenes) {
                // 获取场景的条件
                List<IotSceneConditionDO> conditions = conditionMapper.selectListBySceneId(scene.getId());
                // 获取场景的动作
                List<IotSceneActionDO> actions = actionMapper.selectListBySceneId(scene.getId());
                
                // 获取用户信息
                IotUserDO user = userMapper.selectById(scene.getUserId());
                
                // 构建场景信息
                Map<String, Object> sceneInfo = new HashMap<>();
                sceneInfo.put("scene", scene);
                sceneInfo.put("user", user);
                sceneInfo.put("conditions", conditions);
                sceneInfo.put("actions", actions);
                
                result.add(sceneInfo);
            }
            
            return CommonResult.success(result);
        } catch (Exception e) {
            log.error("[getAllUserSceneActions][获取场景列表失败]", e);
            return CommonResult.error(500, "获取场景列表失败");
        }
    }

    @GetMapping("/device-nickname/{deviceId}")
    public CommonResult<String> getDeviceNickname(@PathVariable("deviceId") Long deviceId) {
        try {
            // 查询用户设备表获取设备昵称
            String sql = "SELECT custom_device_name FROM iot_user_device WHERE device_id = ? AND deleted = 0 LIMIT 1";
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, deviceId);
            
            if (!results.isEmpty()) {
                String nickname = (String) results.get(0).get("custom_device_name");
                return CommonResult.success(nickname != null ? nickname : "设备" + deviceId);
            }
            
            // 如果没有找到昵称，返回设备ID
            return CommonResult.success("设备" + deviceId);
        } catch (Exception e) {
            log.error("[getDeviceNickname][获取设备昵称失败，设备ID: {}]", deviceId, e);
            return CommonResult.success("设备" + deviceId);
        }
    }

    @GetMapping("/user-devices/{userId}")
    public CommonResult<List<Map<String, Object>>> getUserDevices(@PathVariable("userId") Long userId) {
        try {
            String sql = "SELECT ud.device_id, ud.custom_device_name, d.device_name, d.product_key " +
                        "FROM iot_user_device ud " +
                        "LEFT JOIN iot_device d ON ud.device_id = d.id " +
                        "WHERE ud.user_id = ? AND ud.deleted = 0";
            
            List<Map<String, Object>> devices = jdbcTemplate.queryForList(sql, userId);
            return CommonResult.success(devices);
        } catch (Exception e) {
            log.error("[getUserDevices][获取用户设备失败，用户ID: {}]", userId, e);
            return CommonResult.error(500, "获取用户设备失败");
        }
    }

    @GetMapping("/user-scenes")
    public CommonResult<List<Map<String, Object>>> getUserScenes(@RequestParam("userId") Long userId) {
        try {
            // 获取指定用户的所有场景
            String sql = "SELECT id, name, description, status, create_time, update_time " +
                        "FROM iot_scene " +
                        "WHERE user_id = ? AND deleted = 0 " +
                        "ORDER BY create_time DESC";
            
            List<Map<String, Object>> scenes = jdbcTemplate.queryForList(sql, userId);
            return CommonResult.success(scenes);
        } catch (Exception e) {
            log.error("[getUserScenes][获取用户场景失败，用户ID: {}]", userId, e);
            return CommonResult.error(500, "获取用户场景失败");
        }
    }

    @DeleteMapping("/condition/{id}")
    public CommonResult<Boolean> deleteCondition(@PathVariable("id") Long id) {
        try {
            conditionMapper.deleteById(id);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[deleteCondition][删除条件失败，条件ID: {}]", id, e);
            return CommonResult.error(500, "删除条件失败");
        }
    }

    @PutMapping("/condition/{id}")
    public CommonResult<Boolean> updateCondition(@PathVariable("id") Long id, @RequestBody cn.iocoder.yudao.module.iot.controller.app.scene.vo.IotSceneConditionCreateReqVO reqVO) {
        try {
            cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneConditionDO update = new cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneConditionDO();
            update.setId(id);
            update.setProductId(reqVO.getProductId());
            update.setDeviceId(reqVO.getDeviceId());
            update.setAttr(reqVO.getAttr());
            update.setValue(reqVO.getValue());
            update.setConditionType(reqVO.getConditionType());
            update.setConditionValue(reqVO.getConditionValue());
            update.setOperator(reqVO.getOperator());
            update.setPriority(reqVO.getPriority());
            conditionMapper.updateById(update);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[updateCondition][更新条件失败，条件ID: {}]", id, e);
            return CommonResult.error(500, "更新条件失败");
        }
    }

    @DeleteMapping("/action/{id}")
    public CommonResult<Boolean> deleteAction(@PathVariable("id") Long id) {
        try {
            actionMapper.deleteById(id);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[deleteAction][删除动作失败，动作ID: {}]", id, e);
            return CommonResult.error(500, "删除动作失败");
        }
    }

    @PutMapping("/action/{id}")
    public CommonResult<Boolean> updateAction(@PathVariable("id") Long id, @RequestBody IotSceneActionDO reqVO) {
        try {
            log.info("[updateAction] 开始更新动作，动作ID: {}, 请求数据: {}", id, reqVO);
            
            IotSceneActionDO update = new IotSceneActionDO();
            update.setId(id);
            update.setProductId(reqVO.getProductId());
            update.setDeviceId(reqVO.getDeviceId());
            update.setAttr(reqVO.getAttr());
            update.setValue(reqVO.getValue());
            update.setActionType(reqVO.getActionType());
            update.setActionValue(reqVO.getActionValue());
            update.setDelay(reqVO.getDelay());
            
            // 特殊处理control类型的动作
            if ("control".equals(reqVO.getActionType())) {
                log.info("[updateAction] 检测到control类型动作，动作值: {}", reqVO.getActionValue());
                // 确保control类型的动作值被正确设置
                if (reqVO.getActionValue() != null) {
                    update.setActionValue(reqVO.getActionValue());
                }
            }
            
            actionMapper.updateById(update);
            log.info("[updateAction] 动作更新成功，动作ID: {}", id);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[updateAction][更新动作失败，动作ID: {}]", id, e);
            return CommonResult.error(500, "更新动作失败");
        }
    }

    @DeleteMapping("/{id}")
    public CommonResult<Boolean> deleteScene(@PathVariable("id") Long id) {
        try {
            // 删除场景相关的条件和动作
            conditionMapper.deleteBySceneId(id);
            actionMapper.deleteBySceneId(id);
            // 删除场景
            sceneMapper.deleteById(id);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[deleteScene][删除场景失败，场景ID: {}]", id, e);
            return CommonResult.error(500, "删除场景失败");
        }
    }

    @PutMapping("/{id}")
    public CommonResult<Boolean> updateScene(@PathVariable("id") Long id, @RequestBody IotSceneDO reqVO) {
        try {
            IotSceneDO update = new IotSceneDO();
            update.setId(id);
            update.setName(reqVO.getName());
            update.setStatus(reqVO.getStatus());
            sceneMapper.updateById(update);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[updateScene][更新场景失败，场景ID: {}]", id, e);
            return CommonResult.error(500, "更新场景失败");
        }
    }

    @PutMapping("/{id}/status")
    public CommonResult<Boolean> updateSceneStatus(@PathVariable("id") Long id, @RequestBody Map<String, Integer> request) {
        try {
            Integer status = request.get("status");
            if (status == null || (status != 0 && status != 1)) {
                return CommonResult.error(400, "状态值必须为0或1");
            }
            
            IotSceneDO update = new IotSceneDO();
            update.setId(id);
            update.setStatus(status);
            sceneMapper.updateById(update);
            
            log.info("[updateSceneStatus][更新场景状态成功，场景ID: {}, 状态: {}]", id, status);
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[updateSceneStatus][更新场景状态失败，场景ID: {}]", id, e);
            return CommonResult.error(500, "更新场景状态失败");
        }
    }
} 